import { ref, reactive, computed } from 'vue'
import _ from 'lodash'

export function useForm() {
  const ruleForm: any = ref(null)

  const state = reactive({
    loading: false,
    type: '',
    show: false,
    rules: {},
    currentData: {} as any
  })

  const initData = (data: any) => {
    _(data).forEach((item: any) => {
      if (item.editType) {
        state.currentData[item.prop] = item.defaultValue
        state.currentData['edit'] = true
      }
    })
    console.log(state.currentData)
  }

  const getValue = (list: any, value: any, option: any) => {
    const arr: any = []

    _(list).forEach((item: any) => {
      if (value.indexOf(item[option.value]) > -1) {
        arr.push(item[option.label])
      }
    })

    return arr.toString()
  }

  const showType = computed(() => {
    return () => {
      let data = ''
      switch (state.type) {
        case 'add':
          data = '新增'
          break
        case 'edit':
          data = '编辑'
          break
        case 'view':
          data = '查看'
          break
        case 'none':
          data = ''
          break
      }
      return data
    }
  })

  const showAsterisk = computed(() => {
    return (data: any) => {
      let type = false
      for (const item in state.rules) {
        if (item === data) {
          type = true
          break
        }
      }

      return type
    }
  })

  const validate = () => {
    return new Promise((resolve) => {
      ruleForm.value.validate((valid: any) => {
        resolve(valid)
      })
    })
  }

  const validateRow = (list: any) => {
    return new Promise((resolve) => {
      ruleForm.value.validateField(list, (valid: any) => {
        resolve(valid)
      })
    })
  }

  const resetForm = () => {
    if (!ruleForm.value) return
    ruleForm.value.resetFields()
  }

  const clearValidate = () => {
    if (!ruleForm.value) return
    ruleForm.value.clearValidate()
  }

  return {
    state,
    ruleForm,
    showType,
    showAsterisk,
    initData,
    getValue,
    validate,
    validateRow,
    resetForm,
    clearValidate
  }
}
